<template>
    <vxe-modal v-model="state.visible" v-bind="state.config" @close="closeModel" @hide="closeModel">
        <template #title> 选择客户 </template>
        <template #default>
            <div class="h-full relative overflow-hidden">
                <div class="h-full flex flex-col bg">
                    <queryPanel v-if="!state.queryConfig.simple" :queryConfig="state.queryConfig" @flutterSend="queryTable"></queryPanel>
                    <div class="p-2 w-full h-full overflow-y-auto">
                        <div class="card p-4 h-full rounded">
                            <vxe-grid class="antdesign-vxetable cell-dblclick-vxetable" ref="xGrid" v-bind="state.tableConfig.gridOptions" @checkbox-all="checkBoxClickEvent" @checkbox-change="checkBoxClickEvent" @radio-change="checkBoxClickEvent" v-if="state.tableLoad" @cell-dblclick="cellDblclick">
                                <template #empty> <a-list :data-source="[]" /> </template>
                            </vxe-grid>
                            <div class="p-3 h-full bg-white dark:bg-transparent" v-else>
                                <a-skeleton />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </template>
        <template #footer>
            <div class="p-3 text-center" v-if="true">
                <a-space :size="10">
                    <a-button type="primary" @click="submit">提交</a-button>
                    <a-button @click="closeModel">取消</a-button>
                </a-space>
            </div>
        </template>
    </vxe-modal>
</template>

<script setup>
import { columns, flutter, batchGroup, setTreeData } from './choose'
const emits = defineEmits(['change', 'update:value'])
const props = defineProps({
    customerInfo: {
        type: Array,
        default: [],
    },
})

let state = reactive({
    config: XEUtils.clone(modelConfig, true),
    addRef: undefined,
    batchConfigRef: undefined,
    xGrid: undefined,
    tableConfig: {
        tableId: '选择客户',
        isTree: false,
        isPage: true,
        showBatch: true,
        showImportBut: true,
        showExportBut: false,
        selectItems: [],
        batchGroup: [],
        importUrl: '',
        exportUrl: '',
        queryUrl: '/api/custInfo/query/list',
        gridOptions: XEUtils.clone(tableMixin, true),
    },

    //筛选

    queryConfig: {
        queryPanel: true,
        simple: false,
        flutterTitWidth: '5px',
        flutterAll: true,
        flutter: [],
    },

    query: {},
    router: useRouter(),
    store: useStore(),
})

//双击选中

function cellDblclick(el) {
    state.xGrid.setRadioRow(el.row)
    state.tableConfig.selectItems = [el.row]
    submit()
}

function submit() {
    if (state.tableConfig.selectItems && state.tableConfig.selectItems.length) {
        emits('change', state.tableConfig.selectItems)
        closeModel()
    }
}

/* =================公共函数=================== */

const checkBoxClickEvent = val => {
    if (columns[0].type === 'checkbox') {
        state.tableConfig.selectItems = [...state.xGrid.getCheckboxRecords(), ...state.xGrid.getCheckboxReserveRecords()]
        state.batchConfigRef.setSelectItems(state.tableConfig.selectItems)
    } else if (columns[0].type === 'radio') {
        state.tableConfig.selectItems = [val.row]
        // emit('change', state.tableConfig.selectItems);
    }
}

const queryTable = datas => {
    state.queryConfig.flutter = datas
    state.xGrid.commitProxy('query')
}

/* =================初始化页面=================== */

createTable()
function createTable() {
    if (state.queryConfig.queryPanel) state.queryConfig.flutter = flutter
    if (state.tableConfig.showBatch) state.tableConfig.batchGroup = batchGroup
    createColumnsFull()
    createTableFull()
    state.tableLoad = true
}

//创建表头数据

function createColumnsFull() {
    state.tableConfig.gridOptions.columns = columns
}

//创建表格

function createTableFull() {
    state.tableConfig.gridOptions.id = state.tableConfig.tableId
    state.tableConfig.gridOptions.rowConfig.keyField = 'custId'
    state.tableConfig.gridOptions.proxyConfig.props.result = 'data.records'
    state.tableConfig.gridOptions.proxyConfig.props.total = 'data.total'
    if (!state.tableConfig.isPage) state.tableConfig.gridOptions.pagerConfig.autoHidden = true
    if (state.tableConfig.isTree) {
        state.tableConfig.gridOptions.proxyConfig.props.result = 'data'
        state.tableConfig.gridOptions.proxyConfig.props.total = 'total'
        state.tableConfig.gridOptions.checkboxConfig.checkStrictly = false
        if (!state.tableConfig.isPage) state.tableConfig.gridOptions.pagerConfig.autoHidden = true
        state.tableConfig.gridOptions.treeConfig = {
            transform: true,
            rowField: 'id',
            parentField: 'parentId',
            children: 'children',
            reserve: false,
        }
    }

    state.tableConfig.gridOptions.loading = true
    state.tableConfig.gridOptions.proxyConfig.ajax = {
        query: ({ page, sorts }) => {
            const queryParams = {
                pageNo: page.currentPage,
                pageSize: page.pageSize,
            }
            Object.assign(queryParams, state.query, state.queryConfig.flutter)
            if (sorts[0]) queryParams.sort = sorts[0].property + ',' + sorts[0].order
            return new Promise((resolve, reject) => {
                axios
                    .postJson(`${state.tableConfig.queryUrl}`, queryParams)
                    .then(res => {
                        state.tableConfig.gridOptions.loading = false
                        if (state.tableConfig.isPage) {
                            if (state.tableConfig.isTree) {
                                res.data.data = XEUtils.toTreeArray(res.data.data)
                            }
                        } else {
                            if (state.tableConfig.isTree) res = setTreeData(res)
                        }
                        resolve(res)
                    })
                    .catch(err => {
                        state.tableConfig.gridOptions.loading = false

                        reject()
                    })
            })
        },
    }
}

watch(
    () => props.customerInfo,
    (newVal, oldVal) => {
        if (newVal !== undefined) {
            state.tableConfig.selectItems = newVal
        } else {
            state.tableConfig.selectItems = []
        }
    },
    { deep: true, immediate: false }
)

function openModel() {
    state.config.remember = false
    state.config.width = '860px'
    state.config.height = '90%'
    state.visible = true
    state.loading = false
    if (state.xGrid) {
        state.xGrid.commitProxy('query')
        if (!state.tableConfig.selectItems.length) {
            state.xGrid.clearRadioRow()
            state.xGrid.clearRadioReserve()
        }
    }
}

function closeModel() {
    state.loading = true
    state.visible = false
}

defineExpose({
    closeModel,
    openModel,
})

const { xGrid, addRef, batchConfigRef } = toRefs(state)
</script>

<style>
.cell-dblclick-vxetable * {
    user-select: none;
}
</style>
